package top.syfy.jwt.jwtdemo.util;

import org.springframework.util.StringUtils;
import top.syfy.jwt.jwtdemo.exception.CustomerException;
import top.syfy.jwt.jwtdemo.message.CodeEnum;
import javax.servlet.http.HttpServletRequest;

/**
 * 从请求头中获取token令牌
 *
 * @author syfy
 * @date 2021/03/10
 */
public class TokenUtil {

	/**
	 * 从请求头中获取token令牌
	 *
	 * @param request 本次HTTP请求对象
	 * @return token令牌
	 */
	public static String getTokenFromReqHeader(HttpServletRequest request) {
		/*
		    从HTTP请求头中获取令牌信息
				1.通过"Authorization:Bearer <Token>"这种方式添加令牌的请求头,在取得的值为"Bearer Token值"格式, 需要从空格之后取值
				2.直接在请求头中设置"Authorization:<Token>"
		 */
		String token = request.getHeader("Authorization");
		if (!StringUtils.hasLength(token)) {
			throw new CustomerException(CodeEnum.EMPTY_TOKEN);
		}
		if (StringUtils.startsWithIgnoreCase(token, "Bearer")) {
			token = token.split(" ")[1];
		}
		return token;
	}
}
